<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/7/20 下午3:40
 * +-------------------------------------------------------------
 */

namespace app\common\traits;

use app\common\service\annotation\NodeAnnotation;
use app\common\service\UploadService;
use app\Request;
use think\response\Json;

trait UploadTrait
{
    /**
     * @NodeAnnotation (title="上传文件")
     */
    public function upload(Request $request): Json|null
    {
        $this->checkPost();

        $data = [
                'storage_type' => $request->post('upload_type','local'),
                'file'         => $request->file('file')
        ];

        $uploadConfig = sysConfig('upload');

        $uploadConfig['upload_type'] = $uploadConfig['upload_type'] ?? 'local';


        empty($data['storage_type']) && $data['storage_type'] = $uploadConfig['upload_type'];

        $storage_type = $uploadConfig['upload_type'];

        $this->sceneValidate($data, 'upload');

        $appNameId = $this->appName == 'admin' ? $this->groupId : $this->companyId;

        try {
            $upload = UploadService::instance()->setConfig($uploadConfig)
                                   ->setIntConfig($appNameId, $this->uid, $storage_type)
                                   ->$storage_type($data['file'], $this->uid);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $code = $upload['code'] ?? 0;
        if ($code == 0) {
            return $this->error($upload['data'] ?? '');
        }
        return $this->success($upload['data'] ?? '', '上传成功');
    }
}